package cn.hinglo.gameclaw.data.exception;


import cn.hinglo.gameclaw.data.entity.Result;
import cn.hinglo.gameclaw.data.utils.ResultUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;

/**
 * @createTime: 2018/1/4
 * @author: HingLo
 * @description: 统一异常处理类
 */
@ControllerAdvice
public class ExceptionUtils {
    private static Logger logger = LoggerFactory.getLogger(ExceptionUtils.class);

    private Integer code;
    private String message;


    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public Result handle(Exception e) {
        if (e instanceof ResultException) {
            ResultException resultException = (ResultException) e;
            setCodeAndMessage(resultException.getCode(), resultException.getMessage());
            logger.info("自定义的异常:{}", e.getMessage());
        } else if (e instanceof DataAccessException) {
            setCodeAndMessage(100, "数据库操作异常");
            logger.info("数据库异常：{}", e.getMessage());
        } else if (e instanceof ServletException) {
            setCodeAndMessage(500, e.getMessage());
            logger.info("登录已过期,请重新登录：{}", e.getMessage());
        } else {
            setCodeAndMessage(300, e.getMessage());
            logger.info("其他类型的异常：{}", e.getMessage());
        }
        e.printStackTrace();
        logger.info(".......................异常捕获结束............................");
        return ResultUtils.error(code, message);
    }

    private void setCodeAndMessage(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

}
